package com.cn.main.framework;

import com.cn.main.framework.annotation.ZxFeign;
import com.cn.main.framework.proxy.RunFactoryBean;
import com.cn.main.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.web.client.RestTemplate;

/**
 * user : chenyuncong
 * create_time : 2022/9/3
 */

public class RunFactoryBeanDefinitionRegistry implements ImportBeanDefinitionRegistrar {


    private RestTemplate restTemplate = new RestTemplate();

    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata,
                                        BeanDefinitionRegistry beanDefinitionRegistry) {
        Class<?> beanClazz= UserService.class;
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz);
        GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();

        ZxFeign feign = beanClazz.getAnnotation(ZxFeign.class);
        MutablePropertyValues propertyValues = definition.getPropertyValues();
        propertyValues.add("interfaceType", beanClazz);
        propertyValues.add("serviceName", feign.value());
        propertyValues.add("restTemplate", restTemplate);
        definition.setBeanClass(RunFactoryBean.class);
        definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);

        beanDefinitionRegistry.registerBeanDefinition(beanClazz.getSimpleName(), definition);
    }
}

